<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class AdminController extends Controller
{
    //
    public function login()
    {
        return view("admin.login.login");
    }

    public function loginCheck(Request $request)
    {
        $this->validate($request,[
            'name'=>"required|max:20|min:2",
            "password"=>"required|max:20|min:2",
        ]);
        $user = request(["name","password"]);
        if ( \Auth::guard("admin")->attempt($user)){
            return [
                'error'=>0,
                "info"=>"登陆成功"
            ];
        }else{
            return[
                "error"=>1,
                "info"=>"账号密码错误",
            ];
        }
    }
    public function logout()
    {
        \Auth::guard("admin")->logout();

        return redirect("/admin/login");
    }

    public function index()
    {
        $admin = \Auth::guard("admin")->user();
        return view("admin.index.index",compact("admin"));
    }

    public function welcome()
    {

        return view("admin.index.welcome");
    }

    public function userlist(Request $request)
    {
        $where = [];
        if(!empty($request->start)){
            $where[] = ['created_at',">",$request->start];
        }
        if(!empty($request->end)){
            $where[] = ['created_at',"<",$request->end];
        }
        if(!empty($request->name)){
            $where[] = ['name',$request->name];
        }
        $users = User::where($where)->paginate(1);

        return view("admin.user.list",compact("users","where","request"));
    }

    public function delUser(User $user)
    {
        if ($user->status ==1){
            $user->status =0;
        }else{
            $user->status =1;
        }
        $user->save();
    }

    public function delUserAll(Request $request)
    {
        $users = User::find($request->data);
        foreach ($users as $user){
            if ($user->status = 1){
                $user->status = 0;
            }else{
                $user->status = 1;
            }
            $user->save();
        }
    }
}
?>
